package me.leiusual.sharing.widget

import android.content.Context
import android.os.CountDownTimer
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import kotlin.math.roundToInt

/**
 * Create by leiusual on 2018/7/21
 */
class CountDownTextView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {

  private var oldText: CharSequence? = null

  private val countDownTimer = object : CountDownTimer(45_000, 1_000) {

    override fun onTick(millisUntilFinished: Long) {
      text = "${(millisUntilFinished / 1000.0).roundToInt()}s后重试"
    }

    override fun onFinish() {
      text = oldText
      isEnabled = true
    }
  }

  fun startTimber() {
    isEnabled = false

    oldText = text

    countDownTimer.cancel()
    countDownTimer.start()
  }

  override fun onDetachedFromWindow() {
    countDownTimer.cancel()
    super.onDetachedFromWindow()
  }
}